/**
* AutoSWF - Cody Cushing. March 26, 2009
* Copyright (c) 2009 Cody Cushing
* No use restrictions. Maintain this notice in all versions. 
**/

package com.autoswf.core
{
	import flash.events.Event;
	
	
	/**
	 * Mediator for moving objects between links. Holds object reference, path information and arguments.
	 */
	public class Transport
	{
		protected static const DELIM:String = Delimiters.PATH_DELIMITER;
		
		
		protected var _address:Array;
		
		
		/** The stack of path ids concatenated to string form. */
		public function get path():String
		{
			return _address.join(DELIM);
		}
		
		
		/** The top object id on the path stack. If there are no path ids, this will be the payload. */
		public function get proposition():*
		{
			return _address[0] || _message;
		}
		
		
		protected var _message:Object;
		
		/** The bottom object on the path stack--payload of the transport object--typically an event. */
		public function get message():*
		{
			return _message;
		}
		
		
		protected var _arguments:Array;
		public function get arguments():Array
		{
			return _arguments;
		}
		
		
		/**
		 * Constructor
		 * 
		 * @param message  An object of some sort to be acted upon at an endpoint.
		 */
		public function Transport(message:* = null)
		{
			_message = message;
			_address = [];
		}
		
		
		/** @param value  "->" delimited string of path ids */
		public function setPath(value:String):Transport
		{
			if(_address)
			{
				var addPath:Array = value.split(DELIM);
				_address = _address.concat(addPath);
			}
			else
			{
				_address = value.split(DELIM);
			}
			
			if(_message == null)
			{
				_message = _address[_address.length - 1];
			}
			
			return this;
		}
		
		
		/** @param arguments  An array of arguments that can be applied to a method. */
		public function setArguments(arguments:Array):Transport
		{
			_arguments = arguments;
			
			return this;
		}
		
		
		public function addPath(id:String):void
		{
			_address.unshift(id);
		}

		
		public function removePath():String
		{
			return _address.shift();
		}
		
		
		/** Creates a path id from the node ids. If message is an event, its type is appended. */
		public function toString():String
		{
			var str:String = path; /* Convert address nodes to "->" delimted string */
			
			if(_message is Event) /* last param is an event, add event type to path id */
			{
				return (str == "") ? Event(_message).type : str + DELIM + Event(_message).type;
			}
			
			/* stringify param and add to path */
			return (str == "") ? _message.toString() : str + DELIM + _message.toString();
		}
	}
}